import React from 'react'
import {connect} from 'react-redux'
import { Row, Col, Timeline, message, Spin, Button, Select, InputNumber, Modal, Input } from 'antd';
import {deepFullCopy, messages, queryCurrencyPrecision} from "share/common";
import 'styles/loan-billing/view-line.scss'
import moment from "moment/moment";
import borrowService from "containers/loan-billing/borrow-and-return.service";
import menuRoute from "routes/menuRoute";
const TimelineItem = Timeline.Item;
const { confirm } = Modal;
const { TextArea } = Input
class turnPermanent extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      recordInfo: {},
      loading: false,
      contractInfo: {},
      mode: '',
      toForeverAmount: 0,
      businessCode: '',
      buttonLoading: false,
      loanDetail: menuRoute.getRouteItem('line-loan-detail'),
    }
  }

  componentWillReceiveProps(nextProps) {
    if(nextProps.turnPermanentFrame === this.props.turnPermanentFrame){
      return -1;
    }
    if(!nextProps.turnPermanentFrame){
      this.setState({recordInfo: {}});
      return -1;
    }
    this.setState({loading: true});
    Promise.all([
      borrowService.getLineInfo(nextProps.viewId),
      borrowService.getLineDetail(nextProps.viewId)
    ]).then(res => {
      this.setState({recordInfo: res[1].data, loading: false, contractInfo: res[0].data, mode: nextProps.mode, toForeverAmount: nextProps.mode == 'edit' ? res[1].data.toForeverAmount : res[1].data.stayWriteOffAmount, businessCode: nextProps.businessCode });
    }).catch(() => {
      this.setState({loading: false});
      message.error(messages('loan-billing.key25')/*系统异常*/);
    });
  }

  changeAmount = (value) => {
    this.setState({
      toForeverAmount: value
    })
  }

  submit = () => {
    const { toForeverAmount, recordInfo, mode } = this.state;
    const  { onClose } = this.props
    if (!recordInfo.remark || recordInfo.remark.length === 0) {
      message.warning('请填写转永久原因');
      return false;
    }
    if (toForeverAmount) {
      if (toForeverAmount > recordInfo.stayWriteOffAmount) {
        message.warning('转永久金额大于可转金额，请修改');
      } else {
        this.setState({ buttonLoading: true })
        if (mode === 'add') {
          const params = {
            loanLineId: recordInfo.id,
            toForeverAmount,
            delayFlag: 2,
            remark: recordInfo.remark
          };
          borrowService.handleDelayDateOrToForeverAmount(params).then(res => {
            if (res.status === 200) {
              message.success('转永久金额成功');
              this.setState({ buttonLoading: false })
              if (onClose) {
                onClose()
              }
            }
          }).catch(err => {
            console.log(err)
            this.setState({ buttonLoading: false })
            let _this = this
            if (err.response.data.message.indexOf('删除原有单据') !== -1) {
              confirm({
                title: err.response.data.message,
                okText: '确认',
                onOk() {
                  borrowService.getIngDelayToforeverLoanBill(recordInfo.id).then(data => {
                    // console.log(data)
                    if (data.status === 200) {
                      _this.context.router.push(_this.state.loanDetail.url.replace(':formOID',data.data.formOID).replace(':loanBillOID',data.data.loanBillOID).replace(':backType','history'));
                    }
                  }).catch(error => {
                    message.error(error.response.data.message);
                  })
                },
                onCancel() {},
              });
            } else {
              message.error(err.response.data.message);
            }
          })
        } else {
          const params = {
            loanLineId: recordInfo.id,
            toForeverAmount,
            remark: recordInfo.remark
          };
          borrowService.handleUpdateDelayDateOrForeverAmount(params).then(res => {
            if (res.status === 200) {
              message.success('转永久金额成功');
              this.setState({ buttonLoading: false })
              if (onClose) {
                onClose()
              }
            }
          }).catch(err => {
            console.log(err)
            this.setState({ buttonLoading: false })
            message.error(err.response.data.message);
          })
        }
      }
    } else {
      message.error('请填写转永久金额');
    }
  }

  handleOnRemarkChange = (e) => {
    const tempRecordInfo = deepFullCopy(this.state.recordInfo)
    tempRecordInfo.remark = e.target.value
    this.setState({
      recordInfo: tempRecordInfo
    })
  }

  render(){
    const { recordInfo, loading, contractInfo, mode, toForeverAmount, businessCode, buttonLoading } = this.state;
    if (!recordInfo.id) {
      return null
    }
    return(
      <div className='view-line'>
      <Spin spinning={loading}>
        <div className='stroke-title'><span>{messages('common.baseInfo')/*基本信息*/}</span></div>
        <div>
          <Row>
            <Col span={4}>{messages('loan-billing.key12')/*借款类型*/}：</Col>
            <Col span={19} offset={1}>{recordInfo.loanTypeName}</Col>
          </Row>
          <Row>
            <Col span={4}>{messages('loan-billing.key68')/*收款方*/}：</Col>
            <Col span={19} offset={1}>
              <span className={recordInfo.payeeType === 1002 ? 'table-blue' : 'table-grey'} style={{padding: '3px 5px', marginRight: '10px'}}>{recordInfo.payeeType === 1002 ? messages('loan-billing.key14')/*员工*/ : messages('loan-billing.key15')/*供应商*/}</span>
              {recordInfo.payeeName}
            </Col>
          </Row>
          {/* <Row>
            <Col span={4}>收款账号：</Col>
            <Col span={19} offset={1}>
              <div>账户：{recordInfo.payeeAccountNumber}</div>
              <div>户名：{recordInfo.payeeAccountName}</div>
            </Col>
          </Row> */}
          {mode == 'add' ? <Row>
            <Col span={4}>{messages('loan-billing.key11')/*借款金额*/}：</Col>
            <Col span={19} offset={1} style={{ display: 'flex' }}>
              <Select disabled defaultValue="CNY">
                <Select.Option value="CNY">CNY</Select.Option>
              </Select>
              <InputNumber
                formatter={value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                parser={value => value.replace(/\$\s?|(,*)/g, '')}
                placeholder={messages('common.please.enter')}
                precision={2}
                value={toForeverAmount}
                // max={recordInfo.stayWriteOffAmount}
                style={{ marginLeft: '20px', width: '100px' }}
                onChange={this.changeAmount}
              />
            </Col>
          </Row> : ''}
          {mode == 'edit' ? <Row>
            <Col span={4}>{messages('loan-billing.key11')/*借款金额*/}：</Col>
            <Col span={19} offset={1} style={{ display: 'flex' }}>
              <Select disabled defaultValue="CNY">
                <Select.Option value="CNY">CNY</Select.Option>
              </Select>
              <InputNumber
                formatter={value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                parser={value => value.replace(/\$\s?|(,*)/g, '')}
                placeholder={messages('common.please.enter')}
                precision={2}
                value={toForeverAmount}
                max={recordInfo.oldLoanBillDTO.stayWriteOffAmount}
                style={{ marginLeft: '20px', width: '100px' }}
                onChange={this.changeAmount}
              />
            </Col>
          </Row> : ''}
          {mode == 'read' ? <Row>
            <Col span={4}>{messages('loan-billing.key199')/*转永久金额*/}：</Col>
            <Col span={19} offset={1}>{recordInfo.baseCurrencyCode} {this.filterMoney(recordInfo.amount,queryCurrencyPrecision(recordInfo.currencyCode), true)}</Col>
          </Row> : ''}
          <Row>
            <Col span={4}>{messages('loan-billing.key148')/*预计还款日期*/}：</Col>
            <Col span={19} offset={1}>{recordInfo.planedRepaymentDate ? moment(recordInfo.planedRepaymentDate).format('YYYY-MM-DD') : '-'}</Col>
          </Row>
          {mode == 'read' ? <Row>
            <Col span={4}>{messages('loan-billing.key201')/*原单号*/}：</Col>
            <Col span={19} offset={1}>{recordInfo && recordInfo.oldLoanBillDTO && recordInfo.oldLoanBillDTO.businessCode}</Col>
          </Row> : ''}
          <Row>
            <Col span={4}>转永久原因：</Col>
            {
              mode === 'read' ? <Col span={19} offset={1}>{recordInfo.remark}</Col> : <Col span={19} offset={1}>
                <TextArea onChange={(e) => this.handleOnRemarkChange(e)} value={recordInfo.remark} style={{ width: '60%', height: '100px' }} />
              </Col>
            }
          </Row>
        </div>

      </Spin>
        <div className="slide-footer">
          <Button onClick={this.props.close}>{messages('common.back')/*返回*/}</Button>
          {mode !== 'read' ? <Button loading={buttonLoading} onClick={this.submit} type="primary">{messages('common.ok')/*确定*/}</Button> : ''}
        </div>
      </div>
    )
  }
}

turnPermanent.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state){
  return {

  }
}

export default connect(mapStateToProps)(turnPermanent);
